export default {
  namespaced: true, // 命名空间
  state: {
    cartList: []
  },
  getters: {
    // 勾选数量
    checkedSum (state) {
      const filterList = state.cartList.filter(item => {
        return item.checked
      })
      return filterList.reduce((prev, item) => {
        return item.num + prev
      }, 0)
    },
    // 勾选价格
    checkedPrice (state) {
      const filterList = state.cartList.filter(item => {
        return item.checked
      })
      return filterList.reduce((prev, item) => {
        return item.originprice * item.num + prev
      }, 0)
    },
    // 购物车商品数量
    sumNum (state) {
      return state.cartList.reduce((prev, item) => {
        return prev + item.num
      }, 0)
    }
  },
  mutations: {
    addToCart (state, payload) {
      const list = state.cartList.find(item => item.proid === payload.proid)
      if (list) {
        list.num++
      } else {
        state.cartList.push(payload)
      }
    },
    updateState (state, payload) {
      const list = state.cartList.find(item => item.proid === payload.proid)
      if (list) {
        list.checked = payload.checked
      }
    },
    isState (state) {
      const check = state.cartList.every(item => item.checked)
      state.cartList.forEach(item => {
        item.checked = !check
      })
    },
    subNum (state, payload) {
      state.cartList.forEach(item => {
        if (item.proid === payload) {
          if (item.num > 1) {
            item.num--
          }
        }
      })
    },
    addNum (state, payload) {
      state.cartList.forEach(item => {
        if (item.proid === payload) {
          item.num++
        }
      })
    },
    changeNumber (state, payload) {
      const list = state.cartList.find(item => item.proid === payload.proid)
      if (list) {
        list.num = payload.num
      }
    },
    delete (state, payload) {
      state.cartList = state.cartList.filter(item => {
        return item.proid !== payload
      })
    }
    // setData (state) {
    //   window.localStorage.setItem('cartList', JSON.stringify(state.cartList))
    // },
    // getData (state, payload) {
    //   state.cartList = payload
    // }
  },
  actions: {
    deleteGoods (context, payload) {
      setTimeout(() => {
        context.commit('delete', payload)
      }, 1000)
    }
  }
}
